package com.lh0811.forge.pserv.uacs.server.config.provider;

import com.lh0811.forge.dependency.basic_code.SpringBeanHelper;
import com.lh0811.forge.dependency.security.core.model.entity.SecurityAuthority;
import com.lh0811.forge.pserv.uacs.server.component.data_scope.provider.AbstractSysRuleValueProvider;
import com.lh0811.forge.pserv.uacs.server.repository.dao.UacsTenantDepartmentDao;
import com.lh0811.forge.pserv.uacs.server.repository.dao.UacsTenantPlateUserPostRefDao;
import com.lh0811.forge.pserv.uacs.server.repository.entity.UacsTenantDepartment;
import com.lh0811.forge.pserv.uacs.server.repository.entity.UacsTenantPlateUserPostRef;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class UserDepartmentSysRuleValueProvider extends AbstractSysRuleValueProvider<List<Long>> {

//    @Resource
//    private UacsTenantPlateUserPostRefDao userPostRefDao;

    @Lazy
    @Resource
    private UacsTenantDepartmentDao uacsTenantDepartmentDao;

    @Override
    public List<Long> getRuleValueByCurrentUser(SecurityAuthority securityAuthority) throws Exception {
        List<UacsTenantPlateUserPostRef> userPostRefList = SpringBeanHelper.getBean(UacsTenantPlateUserPostRefDao.class).lambdaQuery()
                .eq(UacsTenantPlateUserPostRef::getTenantId, securityAuthority.getSecurityUser().getCurrTenantInfo().getId())
                .eq(UacsTenantPlateUserPostRef::getPlateUserId, Long.valueOf(securityAuthority.getUserId()))
                .list();
        if (CollectionUtils.isEmpty(userPostRefList)) {
            return null;
        }
        List<Long> departmentIdList = userPostRefList.stream().map(ele -> ele.getDepartmentId()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(departmentIdList)) {
            return null;
        }

        // 获取子部门
        List<Long> reslutIdList = Lists.newArrayList();
        for (Long currDpId : departmentIdList) {
            reslutIdList.add(currDpId);
            List<UacsTenantDepartment> childIdList = uacsTenantDepartmentDao.lambdaQuery().like(UacsTenantDepartment::getRouter, "," + currDpId + ",").list();
            if (!CollectionUtils.isEmpty(childIdList)) {
                reslutIdList.addAll(childIdList.stream().map(ele -> ele.getId()).collect(Collectors.toList()));
            }
        }

        return reslutIdList;
    }
}
